package com.shark.open.config;

import com.google.common.base.Splitter;
import com.shark.model.erp.StationAccessConfModel;
import lombok.Getter;
import lombok.experimental.Accessors;

import java.util.ArrayList;
import java.util.List;

public class ReqContext {
    private static ThreadLocal<AccessContext> ctxAppAccess = new ThreadLocal();

    public ReqContext() {
    }

    public static void setContext(AccessContext ctx) {
        ctxAppAccess.set(ctx);
    }

    public static AccessContext getContext() {
        return ctxAppAccess.get();
    }

    @Getter
    @Accessors(chain = true)
    public static class AccessContext {
        private String accessId;
        private String accessKey;
        private Integer groupId;
        private List<Integer> allowStation = new ArrayList<>();
        private String timespan;
        private String sign;

        public static AccessContext of(StationAccessConfModel accessConf) {
            AccessContext context = new AccessContext();
            context.accessId = accessConf.getAccessId();
            context.accessKey = accessConf.getAccessKey();
            context.groupId = accessConf.getGroupId();
            Splitter.on(",").omitEmptyStrings()
                    .split(accessConf.getAllowStation())
                    .forEach(x -> context.allowStation.add(Integer.valueOf(x)));
            return context;
        }

        public AccessContext updateReq(String timespan, String sign) {
            this.timespan = timespan;
            this.sign = sign;
            return this;
        }
    }
}
